package com.zzf.concurrent.example.atomic.cas.lock;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author GaoFeng2017
 * @date 2019/9/12 10:01
 */
@Slf4j
public class CompareAndSetLock {

    private AtomicInteger atomicInteger;
    private volatile Thread currentThread;

    public CompareAndSetLock() {
        this.atomicInteger = new AtomicInteger();
    }

    public void tryLock() {
        boolean isGetLock = atomicInteger.compareAndSet(0, 1);
        if (!isGetLock) {
            throw new RuntimeException("获取显示锁失败");
        } else {
            this.currentThread = Thread.currentThread();
        }
    }

    public void unlock() {
        if (atomicInteger.get() == 0 || Thread.currentThread() != this.currentThread) {
            return;
        }

        StringBuilder

        atomicInteger.compareAndSet(1, 0);
        log.info("{} is unlock.", Thread.currentThread().getName());
    }
}
